package com.minelx.datamicroscope.core.values;

import com.alibaba.fastjson.JSONObject;
import com.minelx.datamicroscope.common.CommonDatabase;
import com.minelx.datamicroscope.common.CommonDatabases;
import com.minelx.sqlstructures.core.table.ITable;

import java.util.Objects;

public final class CommonTable {

	private final CommonDatabase commonDatabase;

	private final String name;

	private CommonTable(CommonDatabase commonDatabase, String name) {
		this.name = name;
		this.commonDatabase = commonDatabase;
	}

	public CommonField primaryKey() {
		ITable structureTable = commonDatabase.structure().table(name);
		return field(structureTable.primary().getName());
	}

	public CommonField field(String field) {
		return new CommonField(this, field);
	}

	public CommonDatabase commonDatabase() {
		return commonDatabase;
	}

	public String path() {
		return commonDatabase.path() + "@" + name;
	}

	public String name() {
		return name;
	}

	public static CommonTable create(CommonDatabase commonDatabase, String tableName) {
		return new CommonTable(commonDatabase, tableName);
	}

	public static CommonTable from(JSONObject data) {
		return create(CommonDatabase.from(data), data.getString("table"));
	}

	public static CommonTable from(String text) {
		String[] joinedTablePattern = text.split("@");
		return create(CommonDatabases.create(joinedTablePattern[0], joinedTablePattern[1]), joinedTablePattern[2]);
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (o == null || getClass() != o.getClass()) return false;
		CommonTable that = (CommonTable) o;
		return commonDatabase.equals(that.commonDatabase) && name.equals(that.name);
	}

	@Override
	public int hashCode() {
		return Objects.hash(commonDatabase, name);
	}

	@Override
	public String toString() {
		return "CommonTable{" +
				"commonDatabase=" + commonDatabase +
				", name='" + name + '\'' +
				'}';
	}
}
